package com.das.mechanic_base.mvp.view.camera;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.das.mechanic_base.R;
import com.das.mechanic_base.R2;
import com.das.mechanic_base.app.X3AppRouterConstants;
import com.das.mechanic_base.app.X3Constent;
import com.das.mechanic_base.base.X3BaseActivity;
import com.das.mechanic_base.base.X3BasePresenter;
import com.das.mechanic_base.bean.camera.CameraBean;
import com.das.mechanic_base.utils.X3FileUtils;
import com.das.mechanic_base.utils.X3GlideRoundTransform;
import com.das.mechanic_base.utils.X3PictureVideoUtils;
import com.das.mechanic_base.utils.X3ScreenUtils;
import com.das.mechanic_base.utils.X3StatusBarUtil;
import com.das.mechanic_base.utils.X3StringUtils;
import com.das.mechanic_base.widget.X3ViewFinderView;
import com.hjq.toast.ToastUtils;
import com.otaliastudios.cameraview.CameraListener;
import com.otaliastudios.cameraview.CameraView;
import com.otaliastudios.cameraview.PictureResult;
import com.otaliastudios.cameraview.controls.Flash;
import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

@Route(path = X3AppRouterConstants.Router.HOME_CAMERA)
public class X3HomeCameraActivity extends X3BaseActivity {

    @BindView(R2.id.cv_view)
    CameraView cv_view;
    @BindView(R2.id.btn_take)
    Button btn_take;
    private String path;
    @BindView(R2.id.iv_img)
    ImageView iv_img;
    @BindView(R2.id.vf_view)
    X3ViewFinderView vf_view;
    @BindView(R2.id.iv_change)
    ImageView iv_change;
    @BindView(R2.id.ll_top_indicator)
    LinearLayout ll_top_indicator;
    @BindView(R2.id.tv_car_num)
    TextView tv_car_num;
    @BindView(R2.id.tv_dri_lic)
    TextView tv_dri_lic;

    @BindView(R2.id.id_ll_car_dri_album)
    LinearLayout id_ll_car_dri_album;
    @BindView(R2.id.id_ll_car_dri_splash)
    LinearLayout id_ll_car_dri_splash;

    @BindView(R2.id.id_rl_album)
    RelativeLayout id_rl_album;
    @BindView(R2.id.id_rl_change)
    RelativeLayout id_rl_change;

    @BindView(R2.id.iv_car_dri_splash_light)
    ImageView iv_car_dri_splash_light;

    private RequestOptions myOptions;
    private Intent intent;
    private String title;
    private float wigthScale,heightScale;
    private boolean isRecogVin = true;

    //需要文档要求，默认是竖屏
    private boolean isVertical = true;

    //是否是识别车牌
    private boolean isCarNum = false;

    //是否是行驶证
    private boolean isDrivingLicense = false;

    //- 是否是从识别车牌号跳转来。如果是则显示识别行驶证
    private boolean fromCarNumRec = false;
    private boolean isOpenFlash;

    @Override
    protected int getLayoutId() {
        EventBus.getDefault().register(this);
        return R.layout.x3_activity_home_camera;
    }

    @Override
    protected void initView() {

        X3StatusBarUtil.darkMode(this);

        intent = getIntent();

        path = intent.getStringExtra("path");
        title = intent.getStringExtra("title");
        fromCarNumRec = intent.getBooleanExtra("isFromCarNum",false);
        Bundle bundle = intent.getExtras();
        if (bundle.getBoolean("type") || intent.getBooleanExtra("type",false)){
            isCarNum = true;
        }
        vf_view.changeText(title);

        carOrVin();

        vf_view.changeScanRect(isVertical,true);

        cv_view.post(() -> {
            if (isDrivingLicense) {
                wigthScale =   X3ScreenUtils.dipToPx(300, X3HomeCameraActivity.this) * 1f / cv_view.getWidth();
                heightScale =  X3ScreenUtils.dipToPx(200, X3HomeCameraActivity.this) * 1f / cv_view.getHeight();
            } else {
                wigthScale = isVertical == true ? X3ScreenUtils.dipToPx(80, X3HomeCameraActivity.this) * 1f / cv_view.getWidth() : X3ScreenUtils.dipToPx(280, X3HomeCameraActivity.this) * 1f / cv_view.getWidth();
                heightScale = isVertical == true ? X3ScreenUtils.dipToPx(280, X3HomeCameraActivity.this) * 1f / cv_view.getHeight() : X3ScreenUtils.dipToPx(80, X3HomeCameraActivity.this) * 1f / cv_view.getHeight();
            }
        });

        cv_view.addCameraListener(new CameraListener() {
            @Override
            public void onPictureTaken(PictureResult result) {
                super.onPictureTaken(result);
                result.toBitmap(bitmap -> {

                    if (bitmap == null){
                        ToastUtils.show("Photograph fail");
                    }

                    int width = bitmap.getWidth();
                    int height = bitmap.getHeight();
                    int rectWidth = (int) (width * wigthScale);
                    int rectHeight = (int) (height * heightScale);

                    float v1 = width * 1.0f / X3ScreenUtils.getScreenWidth(X3HomeCameraActivity.this);

                    // 裁剪中间区域
                    Bitmap rectBitmap = null;

                    if (isDrivingLicense) {
                        //行驶证模式下不再裁剪图片
                        rectBitmap = bitmap;
                    } else {
                        try {
                            if (isVertical){
                                int i = (int) ((X3ScreenUtils.getScreenHeight(X3HomeCameraActivity.this) - X3ScreenUtils.dipToPx(280,X3HomeCameraActivity.this)) / 2 * v1);
                                if (i + rectHeight > bitmap.getHeight()) {
                                    rectHeight = bitmap.getHeight() - i;
                                }
                                rectBitmap = Bitmap.createBitmap(bitmap,
                                        (bitmap.getWidth() - rectWidth) / 2,
                                        i,
                                        rectWidth, rectHeight);
                                rectBitmap = adjustPhotoRotation(rectBitmap,-90);
                            } else {
                                rectBitmap = Bitmap.createBitmap(bitmap,
                                        (bitmap.getWidth() - X3StatusBarUtil.getStatusBarHeight(X3HomeCameraActivity.this) - rectWidth) / 2,
                                        (bitmap.getHeight() - X3StatusBarUtil.getStatusBarHeight(X3HomeCameraActivity.this) - rectHeight) / 2,
                                        rectWidth, rectHeight);
                            }
                        }catch (Exception e){
                            rectBitmap = bitmap;
                        }
                    }

                    X3FileUtils.saveOriginBitmapCompress(X3HomeCameraActivity.this,rectBitmap, path, path -> {
                        Log.e("x3home_camera","path = " + path);
                        Intent resIntent = getIntent();
                        resIntent.putExtra("isDrivingLicense",isDrivingLicense);
                        setResult(RESULT_OK,getIntent());
                        finish();
                    });
                });
            }
        });

        myOptions = new RequestOptions()
                .centerCrop()
                .dontAnimate()
                .diskCacheStrategy(DiskCacheStrategy.RESOURCE)
                .transform(new X3GlideRoundTransform(this, 6));

        String firstPicture = X3PictureVideoUtils.getFirstPicture(this);

        Glide.with(this).load(firstPicture).apply(new RequestOptions().
                apply(myOptions).error(R.mipmap.x3_car_img_bg).
                placeholder(R.mipmap.x3_car_img_bg)).into(iv_img);
    }

    private void carOrVin(){
        if (isCarNum){
            isVertical = false;
            iv_change.setVisibility(View.GONE);
            id_rl_album.setVisibility(View.GONE);
            id_rl_change.setVisibility(View.GONE);

            id_ll_car_dri_album.setVisibility(View.VISIBLE);
            id_ll_car_dri_splash.setVisibility(View.VISIBLE);

        }else{
            isVertical = true;
            iv_change.setVisibility(View.VISIBLE);
            id_rl_album.setVisibility(View.VISIBLE);
            id_rl_change.setVisibility(View.VISIBLE);

            id_ll_car_dri_album.setVisibility(View.GONE);
            id_ll_car_dri_splash.setVisibility(View.GONE);
        }

        if (fromCarNumRec && X3Constent.isChina()){ // 识别行驶证 在cn的情况下才显示
            ll_top_indicator.setVisibility(View.VISIBLE);
        } else {
            ll_top_indicator.setVisibility(View.GONE);
        }
        changeWH();
    }

    private Bitmap adjustPhotoRotation(Bitmap bm, final int orientationDegree) {
        Matrix m = new Matrix();
        m.setRotate(orientationDegree, (float) bm.getWidth() / 2, (float) bm.getHeight() / 2);
        try {
            Bitmap bm1 = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), m, true);
            return bm1;
        } catch (OutOfMemoryError ex) {
        }
        return null;
    }

    @Override
    protected X3BasePresenter createPresenter() {
        return null;
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(title.equals( getString(R.string.x3_recognize_car_number))){
            MobclickAgent.onPageStart("识别车牌号页");
        }else{
            MobclickAgent.onPageStart("识别VIN页");
        }

        cv_view.open();
    }

    @Override
    protected void onPause() {
        cv_view.close();
        if(title.equals( getString(R.string.x3_recognize_car_number))){
            MobclickAgent.onPageEnd("识别车牌号页");
        }else{
            MobclickAgent.onPageEnd("识别VIN页");
        }
        super.onPause();
    }

    @Nullable
    @OnClick({R2.id.iv_back,R2.id.btn_take,R2.id.iv_img,R2.id.iv_change,R2.id.fl_car_num,R2.id.fl_dri_lic,R2.id.id_ll_car_dri_album,R2.id.iv_car_dri_splash_light})
    public void onViewClick(View view) {
        int id = view.getId();
        if (id == R.id.iv_back) {
            finish();
        } else if (id == R.id.btn_take) {
            if (cv_view == null) {
                ToastUtils.show("camera init fail");
                return;
            }
            cv_view.takePictureSnapshot();
        } else if (id == R.id.iv_img || id == R.id.id_ll_car_dri_album) {// 从相册中选择照片
            Intent intent = new Intent(this, X3CameraPhotoActivity.class);
            intent.putExtra("isAlbum", 1);
            intent.putExtra("allNum", 1);
            startActivity(intent);
            overridePendingTransition(R.anim.activity_enter, 0);
        } else if (id == R.id.iv_change){
            isVertical = !isVertical;
            changeWH();
            vf_view.changeScanRect(isVertical,false);
        } else if (id == R.id.fl_car_num){
            isDrivingLicense = false;
            changeCameraRectParams();
            vf_view.changeScanRect(isVertical,true);
            changeIndicatorBg(true);
        } else if (id == R.id.fl_dri_lic){
            isDrivingLicense = true;
            changeCameraRectParams();
            vf_view.changeDriLicScanRect( true);
            changeIndicatorBg(false);
        } else if (id == R.id.iv_car_dri_splash_light){
            isOpenFlash = !isOpenFlash;
            if (isOpenFlash){
                cv_view.set(Flash.TORCH);
            } else {
                cv_view.set(Flash.OFF);
            }
            if (true) {
                iv_car_dri_splash_light.setImageResource(isOpenFlash ? R.mipmap.x3_light_open : R.mipmap.x3_light_close);
            }
        }
    }

    private void changeIndicatorBg(boolean left){
        if (left){
            tv_car_num.setTextColor(getColor(R.color.black));
            tv_dri_lic.setTextColor(getColor(R.color.white));
            tv_car_num.setBackgroundResource(R.drawable.x3_car_vin_drilic_bg);
            tv_dri_lic.setBackgroundResource(0);
        } else {
            tv_car_num.setTextColor(getColor(R.color.white));
            tv_dri_lic.setTextColor(getColor(R.color.black));
            tv_car_num.setBackgroundResource(0);
            tv_dri_lic.setBackgroundResource(R.drawable.x3_car_vin_drilic_bg);
        }
    }

    private void changeCameraRectParams(){
        if (isDrivingLicense) {
            wigthScale =   X3ScreenUtils.dipToPx(300, X3HomeCameraActivity.this) * 1f / cv_view.getWidth();
            heightScale =  X3ScreenUtils.dipToPx(200, X3HomeCameraActivity.this) * 1f / cv_view.getHeight();
        } else {
            wigthScale = isVertical == true ? X3ScreenUtils.dipToPx(80, X3HomeCameraActivity.this) * 1f / cv_view.getWidth() : X3ScreenUtils.dipToPx(280, X3HomeCameraActivity.this) * 1f / cv_view.getWidth();
            heightScale = isVertical == true ? X3ScreenUtils.dipToPx(280, X3HomeCameraActivity.this) * 1f / cv_view.getHeight() : X3ScreenUtils.dipToPx(80, X3HomeCameraActivity.this) * 1f / cv_view.getHeight();
        }
    }

    private void changeWH(){
        wigthScale = isVertical == true ? X3ScreenUtils.dipToPx(90, X3HomeCameraActivity.this) * 1f / cv_view.getWidth() : X3ScreenUtils.dipToPx(290, X3HomeCameraActivity.this) * 1f / cv_view.getWidth();
        heightScale = isVertical == true ? X3ScreenUtils.dipToPx(280, X3HomeCameraActivity.this) * 1f / cv_view.getHeight() : X3ScreenUtils.dipToPx(80, X3HomeCameraActivity.this) * 1f / cv_view.getHeight();
    }

    /**
     * 从相册中选取图片 或者拍照 数据都会从这个方法进入
     * @param cameraBean
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGetPictureOrVideo(CameraBean cameraBean) {
        if (cameraBean == null) {
            return;
        }
        switch ((int) cameraBean.resultCode) {
            //相册返回 集合
            case X3Constent.CODE_GALLERY_REQUEST:
                if (cameraBean.cameraData == null) {
                    return;
                }
                List<String> pList = (List<String>) cameraBean.cameraData;
                if (X3StringUtils.isListEmpty(pList)) {
                    return;
                }
                intent.putExtra("path",pList.get(0));
                intent.putExtra("isDrivingLicense",isDrivingLicense);
                setResult(RESULT_OK,intent);
                finish();
                break;
            default:
                break;
        }
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {

    }


}
